package com.aispeech.task.executor;

import com.aispeech.task.executor.config.ExecutorConfig;
import com.aispeech.task.executor.service.AsyncTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.event.ContextClosedEvent;

@SpringBootApplication(
        exclude = {RedisRepositoriesAutoConfiguration.class}
)
@ComponentScan("com.aispeech.task")
@Slf4j
public class ExecutorApp implements CommandLineRunner, ApplicationListener<ContextClosedEvent> {
    @Autowired
    AsyncTaskService taskService;

    @Autowired
    ExecutorConfig executorConfig;

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(ExecutorApp.class, args);
        log.info("app:executor started. {}", context.getEnvironment().getProperty("seaweedfs.host"));
    }

    @Override
    public void run(String... args) {
        for (int i = 1; i < executorConfig.getSize() + 1; i++)
            taskService.blockingReceiveInThreadpool(i);
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        taskService.shutdown();
    }
}
